<?php

namespace app\admin\controller;

use app\admin\controller\auth\Group;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\Subject;
use app\admin\model\GradeGroup;
use app\admin\model\SalaryBenchmark;
use app\admin\model\SalaryBenchmarkItem;
use app\admin\model\AdminSalaryBenchmarkItem;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Loader;
use think\Validate;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;

/**
 * 人员管理
 *
 * @icon   fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    /**
     * @var \app\admin\model\Admin
     */
    protected $model = null;
    const ADMIN_AUTH_GROUP = 6; // 管理组pid
    const A_ADMIN_ID = 1; // 最高权限ID    //auth_group表id
    const Z_ADMIN_ID = 6; // 总管理员ID
    const X_ADMIN_ID = 8; // 系统管理员ID
    const R_ADMIN_ID = 9; // 人事管理员ID
    const Y_ADMIN_ID = 10; // 业务管理员ID
    const C_ADMIN_ID = 11; // 财务管理员ID
    const TEACHER = 12; // 普通教师
    const Q_ADMIN_ID = 13; // 其他岗位
    const S_ADMIN_ID = 14; // 数据统计管理员
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');
        $this->childrenAdminIds = $this->auth->getChildrenAdminIds($this->auth->isSuperAdmin());
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds($this->auth->isSuperAdmin());
        $where = [];
        $AuthGroupAccessInfo = AuthGroupAccess::where('uid',$this->auth->id)->find();
        if(empty($AuthGroupAccessInfo))$this->error('登录错误');
        if(!in_array($AuthGroupAccessInfo['group_id'],[self::A_ADMIN_ID,self::Z_ADMIN_ID]))$where['id'] = ['<>','8']; //如果不是总管理员或系统管理员不显示系统管理员
        $groupList = collection(AuthGroup::where('id', '>', 6)->where('status','normal')->select())->toArray();
        //科目列表
        $subject_list = Subject::select();
        //年级组
        $grade_group_list = GradeGroup::select();
        //业务管理员
        $business_administrator_list = $this->model
            ->join('auth_group_access a','id = a.uid')
            ->where(['group_id'=>self::Y_ADMIN_ID])
            ->select();
        //人事管理员
        $personnel_manager_list = $this->model
            ->join('auth_group_access a','id = a.uid')
            ->where(['group_id'=>self::R_ADMIN_ID])
            ->select();
        $groupdata = [];
        foreach ($groupList as &$v){
            $groupdata[$v['id']] = $v['name'];
        }
//        Tree::instance()->init($groupList);
//        if ($this->auth->isSuperAdmin()) {
//            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
//
//            foreach ($result as $k => $v) {
//                $groupdata[$v['id']] = $v['name'];
//            }
//        } else {
//            $result = [];
//            $groups = $this->auth->getGroups();
//            foreach ($groups as $m => $n) {
//                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
//                $temp = [];
//                foreach ($childlist as $k => $v) {
//                    $temp[$v['id']] = $v['name'];
//                }
//                $result[__($n['name'])] = $temp;
//            }
//            $groupdata = $result;
//        }
        $this->view->assign('groupdata', $groupdata);
        $this->view->assign("business_administrator_list", $business_administrator_list);
        $this->view->assign("personnel_manager_list", $personnel_manager_list);
        $this->view->assign("subject_list", $subject_list);
        $this->view->assign("grade_group_list", $grade_group_list);
        $this->view->assign('groupList', $groupList);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
        $this->assignconfig("group_id", $AuthGroupAccessInfo['group_id']);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->alias('a')
                ->field('a.*,ag.uid,ag.group_id,at.name as at_name')
                ->join('auth_group_access ag','a.id = ag.uid')
                ->join('auth_group at','ag.group_id=at.id')
//                ->where('a.id','not in',[1,2])
                ->where($where)
//                ->whereNotIn('a.id',Db::table('b_auth_group_access')->whereIn('group_id',[1,6,8])->column('uid'))
                ->whereNotIn('ag.group_id',[1,6,8])
//                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $v['a.id'] = $v['id'];
                $v['at.name'] = $v['at_name'];
                $v['a.createtime'] = $v['createtime'];
            }
            unset($v);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            $admingroup_ids = $this->request->post("admingroup_ids");
            $group = $this->request->post("group");

            if ($params) {
                Db::startTrans();
                try {
                    $check_pwd = check_pwd($params['password']);
                    if($check_pwd['code'] != 1)exception($check_pwd['msg']);

                    $admin_info = $this->model->where('username', $params['username'])->find();
                    if (!empty($admin_info)) exception('该账户已存在');
                    $admin_info = $this->model->where('id_card', $params['id_card'])->find();
                    if (!empty($admin_info)) exception('该身份证号已存在');
                    // yanzheng
                    $auth_group = Db::table('b_auth_group')->where('id',$group)->find();
                    if($auth_group['check_auth'] != 0 && !$params['signature']){
                        exception('请上传电子签章');
                    }
//                    $asbi_template_ids = Db::table('b_admin_group_asbi')->whereIn('group_id',$admingroup_ids)->column('asbi_template_id');
//                    $h_salary_benchmark_ids = Db::table('b_auth_asbi_template_item')->whereIn('template_id',$asbi_template_ids)->column('salary_benchmark_id');
//                    $salary_benchmark_item = Db::table('b_salary_benchmark_item')->whereIn('id',$params['salary_benchmark_item_id'])->column('salary_benchmark_id');
//                    if(!empty($h_salary_benchmark_ids) && !empty($salary_benchmark_item)){
//                        foreach ($h_salary_benchmark_ids as $h_salary_benchmark_id){
//                            if(in_array($h_salary_benchmark_id,$salary_benchmark_item)){
//                                exception('基准项和人员组冲突!');
//                            }
//                        }
//                    }

                    $check_data = $this->_check_data($params);

                    if($check_data['code'] != 1)exception($check_data['msg']);
                    $params = $check_data['data'];
                    $salt = Random::alnum();
                    $params['password'] =  md5(md5($params['password']) . $salt);
                    $params['salt'] = $salt;
                    $params['avatar'] = '/assets/img/avatar.png';
                        $result = $this->model->allowField(true)->save($params);

                    if(!$result)exception('添加失败');
//                    if($admingroup_ids){
//                        $admingroup_ids = explode(',',$admingroup_ids);
//                        $admingroup_data = [];
//                        foreach ($admingroup_ids as $admingroup){
//                            $admingroup_data[] = [
//                                'uid'=>$this->model->id,
//                                'group_id'=>$admingroup,
//                            ];
//                        }
//                        Db::table('b_admin_group_access')->insertAll($admingroup_data);
//                    }


//                    model('AuthGroupAccess')->save([
//                        'uid'=>$this->model->id,
//                        'group_id'=>$group
//                    ]);
                    //添加用户的自定义基准项
                    $add_salary_res = $this->_add_salary($params['salary_benchmark_item_id'],$this->model->id);
                    if($add_salary_res['code'] != 1)exception($add_salary_res['msg']);

                    //添加用户组
                    $dataset = ['uid' => $this->model->id, 'group_id' => $group];
                    $auth_group_access_res = model('AuthGroupAccess')->save($dataset);
                    if(!$auth_group_access_res)exception('添加失败2');
                    Db::commit();
                } catch (\Throwable $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }



    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->group_id = model('AuthGroupAccess')->where(['uid'=>$row->id])->value('group_id');
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            $admingroup_ids = $this->request->post("admingroup_ids");
            $group = $this->request->post("group");
            if ($params) {
                Db::startTrans();
                try {

                    $admin_info = $this->model->where(['id_card'=>$params['id_card'],'id'=>['<>',$row->id]])->find();
                    if (!empty($admin_info)) exception('该身份证号已存在');

                    // yanzheng
                    $auth_group = Db::table('b_auth_group')->where('id',$group)->find();
                    if($auth_group['check_auth'] != 0 && !$params['signature']){
                        exception('请上传电子签章');
                    }
                    $asbi_template_ids = Db::table('b_admin_group_asbi')->whereIn('group_id',$admingroup_ids)->column('asbi_template_id');
                    $h_salary_benchmark_ids = Db::table('b_auth_asbi_template_item')->whereIn('template_id',$asbi_template_ids)->column('salary_benchmark_id');
                    $salary_benchmark_item = Db::table('b_salary_benchmark_item')->whereIn('id',$params['salary_benchmark_item_id'])->column('salary_benchmark_id');

                    if(!empty($h_salary_benchmark_ids) && !empty($salary_benchmark_item)){
                        foreach ($h_salary_benchmark_ids as $h_salary_benchmark_id){
                            if(in_array($h_salary_benchmark_id,$salary_benchmark_item)){
                                exception('基准项和人员组冲突!');
                            }
                        }
                    }

                    $check_data = $this->_check_data($params);
                    if($check_data['code'] != 1)exception($check_data['msg']);
                    $params = $check_data['data'];
                    if(!empty($params['password'])){
                        $check_pwd = check_pwd($params['password']);
                        if($check_pwd['code'] != 1)exception($check_pwd['msg']);
                        $salt = Random::alnum();
                        $params['password'] =  md5(md5($params['password']) . $salt);
                        $params['salt'] = $salt;
                    }else{
                        unset($params['password']);
                    }
                    $result = $row->allowField(true)->save($params);

                    if(!$result)exception('更新失败');
                    //添加用户的自定义基准项
                    $add_salary_res = $this->_add_salary($params['salary_benchmark_item_id'],$row->id);
                    if($add_salary_res['code'] != 1)exception($add_salary_res['msg']);

//                    $admingroup_ids = explode(',',$admingroup_ids);
//                    $admingroup_data = [];
//                    if($admingroup_ids){
//                        Db::table('b_admin_group_access')->where('uid',$row->id)->delete();
//                        foreach ($admingroup_ids as $admingroup){
//                            if($admingroup){
//                                $admingroup_data[] = [
//                                    'uid'=>$row->id,
//                                    'group_id'=>$admingroup,
//                                ];
//                            }
//                        }
//                        if($admingroup_data){
//                            Db::table('b_admin_group_access')->insertAll($admingroup_data);
//                        }
//                    }
//                    Db::table('b_admin_group_access')->where('uid',$row->id)->delete();
                    model('AuthGroupAccess')->where('uid',$row->id)->update(array('group_id'=>$group));

//                    if($row->group_id != $params['group']){
//                        if($row->group_id == self::Y_ADMIN_ID  || $row->group_id == self::R_ADMIN_ID){
//                            $bind_admin_info = $this->model->where(['business_administrator_id|personnel_manager_id'=>$row->id])->find();
//                            if(!empty($bind_admin_info))exception('请先将该人事/业务管理员绑定的员工解绑');
//                        }
//                        $auth_group_access_res = model('AuthGroupAccess')->where('uid',$row->id)->update(array('group_id'=>$params['group']));
//                        if(!$auth_group_access_res)exception('更新失败2');
//                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $admingroup_ids = Db::table('b_admin_group_access')->where('uid',$row['id'])->column('group_id');
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        $this->view->assign("admingroup_ids", implode(',',$admingroup_ids));
        $row->f_major = explode(',',$row->f_major);
        $row->salary_benchmark_item_arr = collection(AdminSalaryBenchmarkItem::with(['salary','item'])->where(['admin_id'=>$row->id])->select())->toArray();
        return $this->view->fetch();
    }


    /**
     * 冻结
     */
    public function freeze($ids = null)
    {

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $admin_status = 'hidden';
                $res = $row->save(array('status'=>$admin_status));
                if (!$res)exception('冻结失败');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        return $this->view->fetch();
    }

    /**
     * 解冻
     */
    public function unfreeze($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $admin_status = 'normal';
                $res = $row->save(array('status'=>$admin_status));
                if (!$res)exception('解冻失败');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        return $this->view->fetch();
    }

    /**
     * 获取教师列表
     */
    public function teacher_list()
    {
        $type = isset($this->request->param()['custom']['type']) ? $this->request->param()['custom']['type'] : 1;
        $where['ag.group_id'] = self::TEACHER;
        if($type != 1)$where['ag.group_id'] = ['in',array(self::R_ADMIN_ID,self::Y_ADMIN_ID,self::C_ADMIN_ID,self::Q_ADMIN_ID,self::S_ADMIN_ID)];
        $list = $this->model->teacher_list($where);
        $total  = count($list);
        return json(array('list'=>$list,'total'=>$total));
    }
    
    /**
     * 导入
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $success_num = $error_num = 0;
        $msg = '';
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            if($maxColumnNumber != 6)exception('文档格式不正确');
            if($allRow < 1)exception('未读取到数据');
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                if(isset($values[0]) && !empty($values) && $values[0]){
//                    switch ($values[0]){
//                        case '系统管理员':
//                            $group_id = self::X_ADMIN_ID;
//                            break;
//                        case '人事管理员':
//                            $group_id = self::R_ADMIN_ID;
//                            break;
//                        case '业务管理员':
//                            $group_id = self::Y_ADMIN_ID;
//                            break;
//                        case '财务管理员':
//                            $group_id = self::C_ADMIN_ID;
//                            break;
//                        case '普通教师':
//                            $group_id = self::TEACHER;
//                            break;
//                        case '其他岗位':
//                            $group_id = self::Q_ADMIN_ID;
//                            break;
//                        case '统计数据管理员':
//                            $group_id = self::S_ADMIN_ID;
//                            break;
//                        default:
//                            $group_id = 0;
//                            break;
//                    }
                    $group_id = AuthGroup::where('name',$values[0])->value('id');
                    if(!$group_id){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：身份不匹配导入失败</br>';
                        continue;
                    }
                    $params = array(
                        'nickname' => $values[1],
                        'mobile' => $values[2],
                        'id_card' => $values[3],
                        'username' => $values[4],
                        'password' => $values[5],
                    );
                    $check_phone = check_phone($params['mobile']);
                    if($check_phone['code'] != 1){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.$check_phone['msg'].'导入失败</br>';
                        continue;
                    };

                    $check_identity_card = check_identity_card($params['id_card']);
                    if($check_identity_card['code'] != 1){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.$check_identity_card['msg'].'导入失败</br>';
                        continue;
                    }

                    $check_pwd = check_pwd($params['password']);
                    if($check_pwd['code'] != 1){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.$check_pwd['msg'].'导入失败</br>';
                        continue;
                    }

                    $validate = $this->validate($params, 'Admin.admin_import');
                    if ($validate !== true){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.$validate.'导入失败</br>';
                        continue;
                    }

                    $admin_info = $this->model->where('id_card', $params['id_card'])->find();
                    if (!empty($admin_info)){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'该身份证号已存在导入失败</br>';
                        continue;
                    }

                    $admin_info = $this->model->where('username', $params['username'])->find();
                    if (!empty($admin_info)){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'该账户已存在导入失败</br>';
                        continue;
                    }

                    $salt = Random::alnum();
                    $params['password'] =  md5(md5($params['password']) . $salt);
                    $params['salt'] = $salt;
                    $params['avatar'] = '/assets/img/avatar.png';

                    Db::startTrans();
                    try{
                        $result = $this->model->create($params);
                        if(!$result){
                            $error_num ++;
                            exception('行号：'.$currentRow.'导入失败1</br>');
                        }
                        $uid = $result->id;
                        //添加用户组
                        $dataset = ['uid' =>$uid, 'group_id' => $group_id];
                        $auth_group_access_res = AuthGroupAccess::create($dataset);
                        if(!$auth_group_access_res){
                            $error_num ++;
                            exception('行号：'.$currentRow.'导入失败2</br>');
                        }
                        Db::commit();
                    }catch (\Throwable $e){
                        $msg .= $e->getMessage();
                        Db::rollback();
                        continue;
                    }

                    $success_num ++;
                }
            }
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }
        $msg = '导入失败：'.$error_num.'</br>'. $msg;
        $this->success('导入成功:'.$success_num.'</br>'.$msg);
    }

    public function _check_data($params)
    {
        try{
            $check_phone = check_phone($params['mobile']);
            if($check_phone['code'] != 1)exception($check_phone['msg']);

            $check_identity_card = check_identity_card($params['id_card']);
            if($check_identity_card['code'] != 1)exception($check_identity_card['msg']);

//            if($params['group'] != self::TEACHER){
//                $params['major'] = $params['f_major'] = $params['grade_group'] = $params['business_administrator_id'] = $params['personnel_manager_id']= 0;
//                $validate = $this->validate($params, 'Admin.add');
//            }else{
//                $params['f_major'] = implode(',',$params['f_major']);
//                if(empty($params['f_major']) && empty($params['major']))exception('主科和科任必须选一种');
//                $validate = $this->validate($params, 'Admin.teacher_add');
//            }
//            if ($validate !== true) exception($validate);
        }catch (\Throwable $e){
            return array('code'=>0,'msg'=>$e->getMessage());
        }
        return array('code'=>1,'msg'=>'ok','data'=>$params);
    }

    public function _add_salary($salary_benchmark_item_id,$admin_id)
    {
        try{
            AdminSalaryBenchmarkItem::where('admin_id',$admin_id)->delete();
            if(!empty($salary_benchmark_item_id)){
                $salary_benchmark_item_ids = explode(',',$salary_benchmark_item_id);
//                var_dump($salary_benchmark_item_ids);die();
                if(!empty($salary_benchmark_item_ids)){
                    $admin_salary_arr = [];
                    foreach ($salary_benchmark_item_ids as $v){
                        $SalaryBenchmarkItemInfo = SalaryBenchmarkItem::where(['id'=>$v])->find();
                        if(empty($SalaryBenchmarkItemInfo))exception('自定义基准项单选项选择错误');
                        array_push($admin_salary_arr,array(
                            'admin_id' => $admin_id,
                            'salary_benchmark_id' => $SalaryBenchmarkItemInfo['salary_benchmark_id'],
                            'salary_benchmark_item_id' => $SalaryBenchmarkItemInfo['id']
                        ));
                    }
                    $res = (new AdminSalaryBenchmarkItem())->saveAll($admin_salary_arr);
                    if(!$res)exception('添加失败1');
                }
            }
        }catch (\Throwable $e){
            return array('code'=>0,'msg'=>$e->getMessage());
        }
        return array('code'=>1,'msg'=>'ok');
    }


    public function teacher_select(){
        if ($this->request->isAjax()) {
            $clubs_name = $this->request->get('clubs_name');
            $select_type = $this->request->get('select_type');

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $condition = [];
//            $condition['ag.group_id'] = self::TEACHER;
//            if($select_type != 1){
//                unset($condition['ag.group_id']);
//            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if($clubs_name && $clubs_name != 'false'){ // 社团搜索
                $clubs_list = Db::table('b_benchmark_clubs')
                    ->field('i.class_name,i.id,i.week,i.teacher_id')
                    ->alias('c')
                    ->where('c.start_time','<',date('Y-m-d'))
                    ->where('c.end_time','>',date('Y-m-d'))
                    ->join('b_benchmark_clubs_item i','i.b_id = c.id')
                    ->select();
                $ids = [];
                foreach ($clubs_list as &$item){
                    $week = str_replace([1,2,3,4,5,6,0],['周一','周二','周三','周四','周五','周六','周日'],$item['week']);
                    $item['class_name'] = $item['class_name'] .'('.$week.')';
                    if($item['class_name'] == $clubs_name){
                        $ids[] = $item['teacher_id'];
                    }
                }
                $list = Db::table('b_admin a')
                    ->field('a.*,g.name')
                    ->join('b_grade_group g','a.grade_group = g.id')
                    ->join('b_auth_group_access ag','a.id = ag.uid')
                    ->where($where)
                    ->where($condition)
                    ->whereIn('a.id',$ids)
                    ->order('a.id desc')
                    ->paginate($limit)
                    ->each(function($item) use ($clubs_list){
                        foreach ($clubs_list as $i){
                            if($i['teacher_id'] == $item['id']){
                                $item['clubs_id'] = $i['id'];
                            }
                        }
                        return $item;
                    });
            }else{
                $list = Db::table('b_admin a')
                    ->field('a.*,g.name')
                    ->join('b_auth_group_access ag','a.id = ag.uid')
                    ->where($condition)
                    ->join('b_grade_group g','a.grade_group = g.id','LEFT')
                    ->where($where)
                    ->order('a.id desc')
                    ->paginate($limit);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if(isset($v[0]) && $v[0] == "createtime"){
                    $v[0] = "a.createtime";
                }
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }
}
